package com.dl698.axdr;

import com.dl698.asn1.axdr.AxdrType;
import com.dl698.util.ReverseByteArrayInputStream;
import com.dl698.util.ReverseByteArrayOutputStream;

/**
 * GetRequestRecord类
 * 实现记录获取请求的编解码
 * 
 * @author wind
 * @version 1.1.1
 */
public class GetRequestRecord implements AxdrType {

    private byte[] dataCode = null;
    private PIID piid = null;
    private GetRecord getRecord = null;

    public GetRequestRecord() {
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    public void setAll(PIID piid, GetRecord getRecord) {
        this.piid = piid;
        this.getRecord = getRecord;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) {
        int codeLength = 0;

        this.piid = new PIID();
        this.piid.setNumBit(8);
        codeLength += this.piid.decode(input);

        this.getRecord = new GetRecord();
        codeLength += this.getRecord.decode(input);

        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) {
        int codeLength;

        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (int i = this.dataCode.length - 1; i >= 0; i--) {
                try {
                    output.write(this.dataCode[i]);
                } catch (java.io.IOException e) {
                    throw new RuntimeException(e);
                }
            }
        } else {
            if (this.piid != null && this.getRecord != null) {
                codeLength = 0;
                codeLength += this.getRecord.encode(output);
                codeLength += this.piid.encode(output);
            } else {
                throw new RuntimeException("piid or getrecord is null");
            }
        }

        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        try {
            this.encode(revOStream);
        } catch (RuntimeException e) {
            // Handle exception
        }
        this.dataCode = revOStream.getArray();
    }

    @Override
    public String toString() {
        if (this.piid != null && this.getRecord != null) {
            return "sequence: {" + "piid: " + this.piid + ", getRecord: " + this.getRecord + "}";
        } else {
            return "piid || getrecord is null";
        }
    }

    public PIID getPiid() {
        return piid;
    }

    public GetRecord getGetRecord() {
        return getRecord;
    }
}